package com.atguigu.crowd.mvc.handler;

import com.atguigu.crowd.entity.Role;
import com.atguigu.crowd.service.api.RoleService;
import com.atguigu.crowd.util.ResultEntity;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@Controller
public class RoleHandler {
    @Autowired
    private RoleService roleService;

    //返回的不是字符串，会把请求的url中role/get/page/info拿去拼前后缀，所以要加@ResponseBody
    @ResponseBody
    @RequestMapping("/role/get/page/info.json")
    public ResultEntity<PageInfo<Role>> getPageInfo(
            @RequestParam(value = "pageNum",defaultValue = "1") Integer pageNum,
            @RequestParam(value = "pageSize",defaultValue = "5") Integer pageSize,
            @RequestParam(value = "keyword",defaultValue = "") String keyword
    ){
        PageInfo<Role> pageInfo = null;
        // SpringMVC中DispatchServlet有一个大的try/catch，当执行到CrowdExceptionResolver.commonResolver时也有try/catch
        // 所以，这里的try/catch可以不用
        try {
            // 获取分页数据，如果操作抛出异常，交给异常映射机制处理
            pageInfo = roleService.getPageInfo(pageNum, pageSize, keyword);
            return ResultEntity.successWithData(pageInfo);
        } catch (Exception e) {
            e.printStackTrace();
            return ResultEntity.failed(e.getMessage());
        }
    }

    @ResponseBody
    @RequestMapping("role/save.json")
//    public ResultEntity<String> saveRole(@RequestParam("roleName") String roleName){
    public ResultEntity<String> saveRole(Role role){ //ajax传的时候roleName要改成和Role的name属性一致
        roleService.saveRole(role);
        return ResultEntity.successWithoutData();
    }

    @ResponseBody
    @RequestMapping("/role/update.json")
    public ResultEntity<String> updateRole(Role role){
        roleService.updateRole(role);

        return ResultEntity.successWithoutData();
    }

    @ResponseBody
    @RequestMapping("/role/remove/by/role/id/array.json")
    public ResultEntity<String> removeByRoleIdArray(@RequestBody List<Integer> roleList){
        roleService.removeRole(roleList);

        return ResultEntity.successWithoutData();
    }
}
